package com.leetcode.根据数据结构分类.图;

import java.util.*;

/**
 * @author: xiaomi
 * @date: 2021/1/12
 * @description: 210. 课程表 II
 * https://leetcode-cn.com/problems/course-schedule-ii/
 */
public class B_210_课程表_II {

    public static void main(String[] args) {
        int numCourses = 2;
        int[][] prerequisites = {{1, 0}};
//        int[][] prerequisites = {{1, 0}, {0, 1}};
//        int[][] prerequisites = {{0, 1}};
        B_210_课程表_II action = new B_210_课程表_II();
        int[] order = action.findOrder(numCourses, prerequisites);
        System.out.println("Arrays.toString(order) = " + Arrays.toString(order));
    }

    /**
     * {@link B_207_课程表} 类似
     *
     * @param numCourses
     * @param prerequisites
     * @return
     */
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        Queue<Integer> queue = new LinkedList<Integer>();
        //HashMap<Integer, Integer> table = new HashMap<>();
        //建立一个数组记录 numCourses 的入度
        int[] array = new int[numCourses];
        //记录每一个课程的出度
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < prerequisites.length; i++) {
            //题目中指向颠倒了
            int to = prerequisites[i][0];
            array[to]++;
            int from = prerequisites[i][1];
            if (map.containsKey(from)) {
                map.get(from).add(to);
            } else {
                ArrayList<Integer> integers = new ArrayList<>();
                integers.add(to);
                map.put(from, integers);
            }
        }
        //找到 入度 = 0
        for (int i = 0; i < numCourses; i++) {
            if (array[i] == 0) {
                queue.offer(i);
            }
        }
        int count = 0;
        int[] res = new int[numCourses];
        while (!queue.isEmpty()) {
            //当前课程的索引
            Integer cur = queue.poll();
            res[count++] = cur;

            //拿到出度
            List<Integer> integers = map.get(cur);
            if (integers == null) {
                continue;
            }
            for (int i = 0; i < integers.size(); i++) {
                if (--array[integers.get(i)] == 0) {
                    queue.offer(integers.get(i));
                }

            }
        }
        return count == numCourses ? res : new int[0];
    }

}
